package br.com.sca.interfaces;

import br.com.sca.entidades.Login;
import br.com.sca.dao.LoginDAO;
import br.com.sca.util.Constantes;
import com.mchange.v2.c3p0.impl.C3P0Defaults;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class LoginFrame extends javax.swing.JInternalFrame {

    private DefaultTableModel tableModel;
    private ListSelectionModel listModel;
    private List<Login> logins;
    private int modo = 2;

    /**
     * Creates new form AlunoFrame
     */
    public LoginFrame() {
        initComponents();
        defineModelo();
        desabilitaCampos();
        desabilitaBotoes();
        atualizaTabela();
    }

    private void defineModelo() {
        /**
         * Define os dados incluso na tabela
         */
        tableModel = (DefaultTableModel) tbLogin.getModel();

        /**
         * Escuta a tabela
         */
        listModel = tbLogin.getSelectionModel();
        listModel.addListSelectionListener(new ListSelectionListener() {

            /**
             * Executa quando um linha da tabela e executado
             *
             * @param e
             */
            @Override
            public void valueChanged(ListSelectionEvent e) {
                mostraDetalheAluno();
            }
        });

        try {
            /*Cria a mascara para o CPF*/
            MaskFormatter cpfMafk = new MaskFormatter("###.###.###-##");
            cpfMafk.setValueContainsLiteralCharacters(false);
            DefaultFormatterFactory formatterCPF = new DefaultFormatterFactory(cpfMafk);
            ftCpf.setFormatterFactory(formatterCPF);

            /*Cria a mascara para o Data Nascimento*/
            /*MaskFormatter nascMafk = new MaskFormatter("##/##/####");
             cpfMafk.setValueContainsLiteralCharacters(true);
             DefaultFormatterFactory formatterNasc = new DefaultFormatterFactory(nascMafk);
             ftNascimento.setFormatterFactory(formatterNasc);*/
        } catch (ParseException ex) {
            Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Mosta o detalhe do aluno da linha selecionada
     */
    private void mostraDetalheAluno() {
        if (tbLogin.getSelectedRow() != -1) {
            int linha = tbLogin.getSelectedRow();
            txNome.setText(logins.get(linha).getNomeCompleto());
            cbSexo.setSelectedItem(logins.get(linha).getSexo());
            ftCpf.setText(logins.get(linha).getCpf());
            ftNascimento.setValue(logins.get(linha).getDataNascimento());
            txLogin.setText(logins.get(linha).getLogin());
            pfSenha.setText(logins.get(linha).getSenha());
            cbAtivo.setSelected(logins.get(linha).isAtivo());
            cbAdministrador.setSelected(logins.get(linha).isAdmin());
        } else {
            limpaTela();
        }
    }

    /**
     * Atualiza a tabela com as inforamações da lista de Alunos
     */
    private void atualizaTabela() {
        LoginDAO ld = new LoginDAO();
        try {
            logins = ld.listaUsuarios();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar a lista de Usuarios", "Erro", JOptionPane.ERROR_MESSAGE);
        }

        int numLinhas = tableModel.getRowCount();

        if (numLinhas > -1) {
            for (int i = 0; i < numLinhas; i++) {
                tableModel.removeRow(0);
            }

            for (int i = 0; i < logins.size(); i++) {
                tableModel.insertRow(i, new Object[]{logins.get(i).getId(), logins.get(i).getNomeCompleto(), logins.get(i).getSexo(), logins.get(i).getCpf()});
            }
        }
    }

    private void desabilitaBotoes() {

        btSalvar.setEnabled(false);
        btCancelar.setEnabled(false);

        btNovo.setEnabled(true);
        btAlterar.setEnabled(true);
        btExcluir.setEnabled(true);

        btPesquisar.setEnabled(true);
    }

    private void habilitaBotoes() {

        btSalvar.setEnabled(true);
        btCancelar.setEnabled(true);

        btNovo.setEnabled(false);
        btAlterar.setEnabled(false);
        btExcluir.setEnabled(false);

        btPesquisar.setEnabled(false);
    }

    /**
     * Habilita os campos para digitação
     */
    private void habilitaCampos() {

        txNome.setEditable(true);
        cbSexo.setEnabled(true);
        ftCpf.setEditable(true);
        ftNascimento.setEditable(true);
        cbAtivo.setEnabled(true);
        cbAdministrador.setEnabled(true);
        pfSenha.setEditable(true);
        txLogin.setEditable(true);
    }

    /**
     * Desabilita os campos pra digitação
     */
    private void desabilitaCampos() {

        txNome.setEditable(false);
        cbSexo.setEnabled(false);
        ftCpf.setEditable(false);
        ftNascimento.setEditable(false);
        cbAtivo.setEnabled(false);
        cbAdministrador.setEnabled(false);
        pfSenha.setEditable(false);
        txLogin.setEditable(false);
    }

    /**
     * Limpa os campos
     */
    private void limpaTela() {

        txNome.setText("");
        cbSexo.setSelectedIndex(0);
        ftCpf.setValue(null);
        ftNascimento.setValue(null);
        cbAtivo.setSelected(false);
        cbAdministrador.setSelected(false);
        pfSenha.setText("");
        txLogin.setText("");

    }

    private void adicionaUsuario() {
        if (txNome.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Campo nome é obrigatório!", "Aviso", JOptionPane.WARNING_MESSAGE);
            txNome.requestFocus();
        } else if (txLogin.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Campo Login é obrigatório!", "Aviso", JOptionPane.WARNING_MESSAGE);
            txLogin.requestFocus();
        } else {
            Login login = new Login();
            LoginDAO ld = new LoginDAO();

            login.setNomeCompleto(txNome.getText().trim());
            login.setSexo((String) cbSexo.getSelectedItem());
            login.setCpf(ftCpf.getText());
            login.setDataNascimento((Date) ftNascimento.getValue());
            login.setLogin(txLogin.getText().trim());
            login.setSenha(pfSenha.getText().trim());
            login.setAtivo(cbAtivo.isSelected());
            login.setAdmin(cbAdministrador.isSelected());
            try {
                ld.salvar(login);
                atualizaTabela();
                desabilitaBotoes();
                desabilitaCampos();
                limpaTela();
                JOptionPane.showMessageDialog(this, "Usuário registrado com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Erro ao tentar gravar o registro", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void alterarUsuario() {
        if (txNome.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "Campo nome é obrigatorio", "Aviso", JOptionPane.WARNING_MESSAGE);
            txNome.requestFocus();
        } else {
            LoginDAO ld = new LoginDAO();
            Login login = new Login();
            login.setId(logins.get(tbLogin.getSelectedRow()).getId());
            login.setNomeCompleto(txNome.getText().trim());
            login.setSexo((String) cbSexo.getSelectedItem());
            login.setCpf((String) ftCpf.getValue());
            login.setLogin(txLogin.getText());
            login.setSenha(pfSenha.getText());
            login.setAtivo(cbAtivo.isSelected());
            login.setAdmin(cbAdministrador.isSelected());

            try {
                ld.alterar(login);
                atualizaTabela();
                desabilitaBotoes();
                desabilitaCampos();
                limpaTela();
                JOptionPane.showMessageDialog(this, "Usuário alterado com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Erro ao tentar alterar o registro", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void excluirLogin() {
        if (tbLogin.getSelectedRow() != -1) {
            LoginDAO ld = new LoginDAO();
            Login login = new Login();
            login = logins.get(tbLogin.getSelectedRow());
            login.setAtivo(false);
            ld.alterar(login);
            JOptionPane.showMessageDialog(this, "Usuário excluido com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
            limpaTela();
            desabilitaBotoes();
            desabilitaCampos();
            atualizaTabela();
        } else {
            JOptionPane.showMessageDialog(this, "Selecione um usuário para exclusão!", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pnCabecalho = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        pnDados = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txNome = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cbSexo = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        ftNascimento = new javax.swing.JFormattedTextField();
        ftCpf = new javax.swing.JFormattedTextField();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        txLogin = new javax.swing.JTextField();
        pfSenha = new javax.swing.JPasswordField();
        cbAtivo = new javax.swing.JCheckBox();
        cbAdministrador = new javax.swing.JCheckBox();
        pnGrid = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbLogin = new javax.swing.JTable();
        jLabel19 = new javax.swing.JLabel();
        txPesquisa = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();
        pnButton = new javax.swing.JPanel();
        btNovo = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        btExcluir = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("SCA - Cadastro de Login");
        setName(""); // NOI18N
        setPreferredSize(new java.awt.Dimension(600, 450));
        getContentPane().setLayout(new java.awt.GridBagLayout());

        pnCabecalho.setBackground(new java.awt.Color(0, 51, 255));

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Cadastro de Login");
        pnCabecalho.add(jLabel1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(pnCabecalho, gridBagConstraints);

        pnDados.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.light"));
        pnDados.setPreferredSize(new java.awt.Dimension(600, 600));

        jLabel2.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Nome.:");

        txNome.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txNome.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                txNomePropertyChange(evt);
            }
        });
        txNome.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txNomeKeyReleased(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Sexo.:");

        cbSexo.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        cbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-", "F", "M" }));

        jLabel6.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setText("CPF.:");

        jLabel7.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel7.setText("Data Nasc.:");

        ftNascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftNascimento.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N

        ftCpf.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N

        jLabel20.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel20.setText("Login.:");

        jLabel21.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel21.setText("Senha.:");

        txLogin.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txLogin.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txLoginFocusLost(evt);
            }
        });

        pfSenha.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N

        cbAtivo.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.light"));
        cbAtivo.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        cbAtivo.setText("Ativo");

        cbAdministrador.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.light"));
        cbAdministrador.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        cbAdministrador.setText("Administrador");

        javax.swing.GroupLayout pnDadosLayout = new javax.swing.GroupLayout(pnDados);
        pnDados.setLayout(pnDadosLayout);
        pnDadosLayout.setHorizontalGroup(
            pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnDadosLayout.createSequentialGroup()
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnDadosLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnDadosLayout.createSequentialGroup()
                                .addComponent(jLabel20)
                                .addGap(9, 9, 9)
                                .addComponent(txLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(pnDadosLayout.createSequentialGroup()
                                    .addGap(1, 1, 1)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txNome, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnDadosLayout.createSequentialGroup()
                                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(cbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(ftCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnDadosLayout.createSequentialGroup()
                                            .addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(pfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(pnDadosLayout.createSequentialGroup()
                                            .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(ftNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                    .addGroup(pnDadosLayout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(cbAtivo, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(163, 163, 163)
                        .addComponent(cbAdministrador)))
                .addContainerGap(214, Short.MAX_VALUE))
        );
        pnDadosLayout.setVerticalGroup(
            pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnDadosLayout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnDadosLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel20))
                    .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(pfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(10, 10, 10)
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbAtivo)
                    .addComponent(cbAdministrador)))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(pnDados, gridBagConstraints);

        pnGrid.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.light"));
        pnGrid.setLayout(new java.awt.GridBagLayout());

        tbLogin.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Nome", "Sexo", "CPF"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbLogin.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tbLogin);
        if (tbLogin.getColumnModel().getColumnCount() > 0) {
            tbLogin.getColumnModel().getColumn(0).setMaxWidth(50);
            tbLogin.getColumnModel().getColumn(1).setMaxWidth(450);
            tbLogin.getColumnModel().getColumn(2).setMaxWidth(60);
            tbLogin.getColumnModel().getColumn(3).setMaxWidth(150);
        }

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(jScrollPane1, gridBagConstraints);

        jLabel19.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel19.setForeground(new java.awt.Color(204, 0, 0));
        jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel19.setText("Pequisar por nome.:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(jLabel19, gridBagConstraints);

        txPesquisa.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txPesquisaActionPerformed(evt);
            }
        });
        txPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txPesquisaKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(txPesquisa, gridBagConstraints);

        btPesquisar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(btPesquisar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(pnGrid, gridBagConstraints);

        pnButton.setLayout(new java.awt.GridBagLayout());

        btNovo.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btNovo.setText("Novo");
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btNovo, gridBagConstraints);

        btAlterar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btAlterar, gridBagConstraints);

        btExcluir.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btExcluir, gridBagConstraints);

        btCancelar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btCancelar.setText("Cancelar");
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btCancelar, gridBagConstraints);

        btSalvar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btSalvar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(pnButton, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        if (modo == Constantes.INSERT_MODEL) {
            adicionaUsuario();
        } else if (modo == Constantes.EDIT_MODEL) {
            alterarUsuario();
        }
    }//GEN-LAST:event_btSalvarActionPerformed

    private void pesquisaUsuarioPorNome() {
        if (txPesquisa.getText().length() > 2) {
            LoginDAO ld = new LoginDAO();
            try {
                logins = ld.pesquisaUsuarioPorNome(txPesquisa.getText());
                txPesquisa.setText("");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Erro ao carregar a lista de alunos", "Erro", JOptionPane.ERROR_MESSAGE);
            }

            int numLinhas = tableModel.getRowCount();
            for (int i = 0; i < numLinhas; i++) {
                tableModel.removeRow(0);
            }

            for (int i = 0; i < logins.size(); i++) {
                tableModel.insertRow(i, new Object[]{logins.get(i).getId(), logins.get(i).getNomeCompleto(), logins.get(i).getSexo(), logins.get(i).getCpf()});
            }
        } else {
            JOptionPane.showMessageDialog(this, "Digite no mínimo 3 caracteres para realizar a pesquisa", "Informação", JOptionPane.INFORMATION_MESSAGE);
        }

    }

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        pesquisaUsuarioPorNome();
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        modo = Constantes.INSERT_MODEL;
        habilitaBotoes();
        habilitaCampos();
        txNome.requestFocus();
    }//GEN-LAST:event_btNovoActionPerformed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        if (tbLogin.getSelectedRow() != -1) {
            modo = Constantes.EDIT_MODEL;
            habilitaBotoes();
            habilitaCampos();
        } else {
            JOptionPane.showMessageDialog(null, "Selecione um aluno para alteração", "Atenção", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        desabilitaBotoes();
        desabilitaCampos();
        atualizaTabela();
        limpaTela();
        modo = 2;
    }//GEN-LAST:event_btCancelarActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        excluirLogin();
    }//GEN-LAST:event_btExcluirActionPerformed

    private void txPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txPesquisaKeyReleased
        txPesquisa.setText(txPesquisa.getText().toUpperCase());
    }//GEN-LAST:event_txPesquisaKeyReleased

    private void txNomeKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txNomeKeyReleased
        txNome.setText(txNome.getText().toUpperCase());
    }//GEN-LAST:event_txNomeKeyReleased

    private void txNomePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txNomePropertyChange
//codigo
    }//GEN-LAST:event_txNomePropertyChange

    private void txPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txPesquisaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txPesquisaActionPerformed

    private void txLoginFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txLoginFocusLost
        LoginDAO ld = new LoginDAO();
        List<Login> l = ld.pesquisaLogin(txLogin.getText());
        if (l.size() > 0 && !txLogin.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Usuário ja cadastrado com esse login", "Aviso", JOptionPane.INFORMATION_MESSAGE);
            txLogin.requestFocus();
        }
    }//GEN-LAST:event_txLoginFocusLost


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JButton btSalvar;
    private javax.swing.JCheckBox cbAdministrador;
    private javax.swing.JCheckBox cbAtivo;
    private javax.swing.JComboBox cbSexo;
    private javax.swing.JFormattedTextField ftCpf;
    private javax.swing.JFormattedTextField ftNascimento;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField pfSenha;
    private javax.swing.JPanel pnButton;
    private javax.swing.JPanel pnCabecalho;
    private javax.swing.JPanel pnDados;
    private javax.swing.JPanel pnGrid;
    private javax.swing.JTable tbLogin;
    private javax.swing.JTextField txLogin;
    private javax.swing.JTextField txNome;
    private javax.swing.JTextField txPesquisa;
    // End of variables declaration//GEN-END:variables
}
